package lq.common.configure;

import lq.common.interceptor.StudyServerProtectInterceptor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 将全局WEB过滤器注册到Spring IOC容器中
 * 使StudyServerProtectInterceptor过滤器生效
 * 并将过滤器添加到Spring的拦截器链中
 */
public class StudyServerProtectConfigure implements WebMvcConfigurer {

    /**
     * @ConditionalOnMissingBean(value = PasswordEncoder.class)注解表示当IOC容器里没有PasswordEncoder类型的Bean的时候，则将BCryptPasswordEncoder注册到IOC容器中。
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(value = PasswordEncoder.class)
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public HandlerInterceptor studyServerProtectInterceptor(){
        return new StudyServerProtectInterceptor();
    }

    /**
     * 添加到spring的拦截器链中
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(studyServerProtectInterceptor());
    }
}
